package cn.dataling.ai.config;

import cn.dataling.ai.component.JacksonComponent;
import cn.dataling.ai.component.XcxComponent;
import cn.dataling.ai.filter.RequestLimitFilter;
import cn.dataling.ai.filter.RequestSourceFilter;
import jakarta.annotation.Resource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @coder taoym
 * @datetime 2021/10/8 16:41
 * @desc 过滤器配置 指定顺序
 * 配置了多个过滤器 由于过滤规则相同 所以这些过滤器为一条过滤器链 filterChain.doFilter()是把request和response交给下一个过滤器 前提是他们的过滤规则相同
 */
@Configuration
@ConditionalOnProperty(value = "spring.profiles.active",havingValue = "prod")
public class FilterConfig {

    @Resource
    private JacksonComponent jacksonComponent;
    @Resource
    private XcxComponent xcxComponent;

    /**
     * @coder taoym
     * @datetime 2021/10/15 22:50
     * @desc 请求源过滤
     */
    @Bean
    public FilterRegistrationBean<RequestSourceFilter> requestSourceFilterBean() {
        FilterRegistrationBean<RequestSourceFilter> filterRegistrationBean = new FilterRegistrationBean<>();

        RequestSourceFilter requestSourceFilter = new RequestSourceFilter(jacksonComponent);

        filterRegistrationBean.setFilter(requestSourceFilter);
        filterRegistrationBean.addUrlPatterns("/*");//配置过滤规则
        filterRegistrationBean.setName("requestSourceFilter");//设置过滤器名称

        return filterRegistrationBean;
    }

    /**
     * @coder taoym
     * @datetime 2021/10/15 22:52
     * @desc 请求限制过滤器
     */
    @Bean
    public FilterRegistrationBean<RequestLimitFilter> requestLimitFilterBean() {
        FilterRegistrationBean<RequestLimitFilter> filterRegistrationBean = new FilterRegistrationBean<>();

        RequestLimitFilter requestLimitFilter = new RequestLimitFilter(jacksonComponent,xcxComponent);

        filterRegistrationBean.setFilter(requestLimitFilter);
        filterRegistrationBean.addUrlPatterns("/websocket/*");//配置过滤规则
        filterRegistrationBean.setName("requestLimitFilter");//设置过滤器名称

        return filterRegistrationBean;
    }
}
